package fr.sigma.labo

import org.codehaus.groovy.grails.web.converters.exceptions.ConverterException
import org.codehaus.groovy.grails.web.json.JSONObject

class AutoStopController {

	AutoStopService autoStopService
		
	def jsonClosure(closure) {
		try {
			JSONObject json = request.JSON
			String id = json.get("id")
			Map data = json.get("data")
			closure(id,data)
		} catch (ConverterException e) {
			log.error( "Erreur json invalide: ${e.message}", e )
			response.status = 400 // Bad Request
			render(contentType: "text/json") {
				["status":"ko", "message":e.getMessage()]
			}
		} catch (Exception e) {
			log.error( "Erreur système : ${e.message}", e )
			response.status = 500
			render(contentType: "text/json") {
				["status":"ko", "message":e.getMessage()]
			}
		}
	}
	
    def put() { 
		jsonClosure { String id, Map data ->
			autoStopService.putData(id, data)
			
			render(contentType: "text/json") {
				["status":"ok","id":id]
			}
		}
	}
	
	def get() {
		jsonClosure { String id, Map data ->
			data = autoStopService.getData(id)
			
			render(contentType: "text/json") {
				["status":"ok", "id":id, "data":data]
			}
		}
	}
	
	def getAll() {
		List datas = autoStopService.getAllData()
		render(contentType: "text/json") {
			datas.each { def d ->
				["data":d]
			}
		}
	}
	
}
